package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        StringBuffer requestUrl = request.getRequestURL();
        System.out.println("LoginAuthInterceptor拦截器：" + requestUrl);
        // 获得前端传递过来的token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)){
            // 校验token
            String userJson = redisTemplate.opsForValue().get("user:login:" + token);
            if (!StringUtils.isEmpty(userJson)){
                SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
                // 存入本地线程
                AuthContextUtil.setUser(sysUser);
            }
        }
        System.out.println("前置拦截器");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空本地线程

        System.out.println("拦截器工作完成后");
    }
}
